package cn.inbot.shopadmin.module.robot.view;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.core.util.Pair;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.GridLayoutManager;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;

import cn.inbot.shopadmin.R;
import cn.inbot.shopadmin.app.AppGlobalData;
import cn.inbot.shopadmin.app.RouterParamsKey;
import cn.inbot.shopadmin.app.RouterUrls;
import cn.inbot.shopadmin.bean.UserVo;
import cn.inbot.shopadmin.event.OnLoginEvent;
import cn.inbot.shopadmin.event.OnLogoutEvent;
import cn.inbot.shopadmin.module.robot.view.adapter.RobotAdapter2;
import cn.inbot.shopadmin.module.robot.viewmodel.RobotViewModel;
import cn.inbot.shopadmin.widget.EmptyLayout;
import cn.inbot.shopadmin.widget.RefreshHeaderLayout;
import cn.inbot.lib.framework.EventManager;
import cn.inbot.lib.framework.annotation.InjectLayout;
import cn.inbot.lib.framework.mvvm.java.PBJVMFragment;
import cn.inbot.lib.framework.router.PBRouter;

import static android.app.Activity.RESULT_OK;
import static cn.inbot.lib.util.ext.ToastExtKt.showToast;

/**
 * Created by shisenkun on 2021/5/10.
 */
@InjectLayout(layoutResId = R.layout.fragment_robot)
public class RobotFragment extends PBJVMFragment<RobotViewModel> {

    public static final int REQUEST_CODE_SCAN_QRCODE = 100;

    private EmptyLayout emptyLayout;
    private AVLoadingIndicatorView loadingView;
    private RecyclerView rvRobot;
    private SmartRefreshLayout smartRefreshLayout;
    private ImageView ivScan;
    private RobotAdapter2 robotAdapter;
    private boolean mIsRefreshing;

    public static RobotFragment create() {
        return new RobotFragment();
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        EventManager.INSTANCE.register(this);
        emptyLayout = new EmptyLayout(requireActivity());
        loadingView = getContentView().findViewById(R.id.loadingView);
        rvRobot = getContentView().findViewById(R.id.rvRobot);
        smartRefreshLayout = getContentView().findViewById(R.id.smartRefreshLayout);
        ivScan = getContentView().findViewById(R.id.ivScan);
        ivScan.setOnClickListener(v ->
                PBRouter.INSTANCE.build(RouterUrls.DEMO_SCAN_QRCODE)
                        .navigation(requireActivity(), REQUEST_CODE_SCAN_QRCODE));
        loadingView.show();
        rvRobot.setVisibility(View.INVISIBLE);
        if (AppGlobalData.sLoginResult != null) {
            viewModel.getRobotVoList();
            viewModel.startPushService();
        } else {
            setupRvRobot(new ArrayList<>(), true);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        immersiveStatusBar(R.color.colorPrimary, true);
        setupToolbar(R.id.toolbar, false, true).setTitle("");
    }

    @Override
    public void startObserve() {
        super.startObserve();
        viewModel.robotVoListResponseWrapper.observe(this, robotVoListResultResponseWrapper -> {
            if (robotVoListResultResponseWrapper.getData() != null) {
                setupRvRobot(robotVoListResultResponseWrapper.getData().getUserVoList(), false);
            } else {
                setupRvRobot(new ArrayList<>(), false);
                showToast("加载失败,错误码:" + robotVoListResultResponseWrapper.getException().getErrorCode());
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCAN_QRCODE && resultCode == RESULT_OK) {
            smartRefreshLayout.autoRefresh();
        }
    }

    @Override
    public void onDestroy() {
        EventManager.INSTANCE.unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(OnLoginEvent event) {
        loadingView.show();
        rvRobot.setVisibility(View.INVISIBLE);
        viewModel.getRobotVoList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(OnLogoutEvent event) {
        setupRvRobot(new ArrayList<>(), true);
        viewModel.startPushService();
    }

    private void setupRvRobot(ArrayList<UserVo> robotList, boolean noLogin) {
        loadingView.hide();
        rvRobot.setVisibility(View.VISIBLE);
        if (robotAdapter == null) {
            robotAdapter = new RobotAdapter2(robotList);
            rvRobot.setLayoutManager(new GridLayoutManager(requireActivity(), 2));
            rvRobot.setAdapter(robotAdapter);

            RefreshHeaderLayout refreshHeaderLayout = new RefreshHeaderLayout(requireActivity());
            refreshHeaderLayout.setPrimaryColors(
                    ContextCompat.getColor(
                            requireContext(),
                            R.color.colorPrimary
                    )
            );
            smartRefreshLayout.setRefreshHeader(refreshHeaderLayout);
            smartRefreshLayout.setEnableRefresh(false);
            smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
                mIsRefreshing = true;
                viewModel.getRobotVoList();
            });
        } else {
            if (!(mIsRefreshing && robotAdapter.getData().size() > 0 && robotList.size() == 0)) {  //过滤之前已经加载成功,但是重新刷新失败的情况
                robotAdapter.setNewInstance(robotList);
                robotAdapter.notifyDataSetChanged();
            }
        }

        robotAdapter.setOnItemClickListener((adapter, view, position) -> {
            ImageView shareView = view.findViewById(R.id.ivRobotModel);
            Bundle bundle = new Bundle();
            bundle.putParcelable(RouterParamsKey.USER_VO, robotList.get(position));
            PBRouter.INSTANCE.build(RouterUrls.DEMO_ROBOT_DETAIL)
                    .with(bundle)
                    .withOptionsCompat(ActivityOptionsCompat.makeSceneTransitionAnimation(
                            requireActivity(),
                            new Pair(shareView, "ivRobotModel")
                    )).navigation(getActivity());
        });
        robotAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.ivNavigation:
                    showToast("导航");
                    break;
                case R.id.ivControl:
                    showToast("本地控制");
                    break;
                case R.id.ivCall:
                    showToast("视频");
                    break;
            }
        });

        if (robotList.size() == 0) {
            emptyLayout.setTip(noLogin ? "未登陆" : "没有机器人");
            robotAdapter.setEmptyView(emptyLayout);
            smartRefreshLayout.setEnableRefresh(false);
            if (mIsRefreshing) {
                smartRefreshLayout.finishRefresh(false);
                mIsRefreshing = false;
            }
        } else {
            smartRefreshLayout.setEnableRefresh(true);
            if (mIsRefreshing) {
                smartRefreshLayout.finishRefresh(true);
                mIsRefreshing = false;
            }
        }
    }

}
